import { useEffect } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { useSelector } from 'react-redux'

const Redirect = () => {
  const token = useSelector((state) => state.user.token)
  const navigate = useNavigate()
  const location = useLocation()
  const redirectPath = location.pathname || '/'

  useEffect(() => {
    if (token) {
      setTimeout(() => {
        navigate('/')
      }, 3000)
      return
    }

    setTimeout(() => {
      navigate(`/login?redirect=${redirectPath}`, { state: { from: redirectPath } })
    }, 3000)
  }, [])

  if (token) {
    return <div>
      当前页面不存在， 404！
    </div>
  }

  return <div>
    无权限， 401！
  </div>
}

export default Redirect